<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input
          placeholder="SPU名称"
          v-model="spuForm.spuName"
        ></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
          placeholder="请选择品牌"
          v-model="spuForm.tmId"
        >
          <el-option
            v-for="tm in trademarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="SPU描述"
          v-model="spuForm.description"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img
            width="100%"
            :src="dialogImageUrl"
            alt=""
          >
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          v-model="saleAttrIdName"
          :placeholder="unUsedSaleAttrList.length>0?`还有${unUsedSaleAttrList.length}未选择`:'没有了!'"
        >
          <el-option
            v-for="(unUsedSaleAttr) in unUsedSaleAttrList"
            :key="unUsedSaleAttr.id"
            :label="unUsedSaleAttr.name"
            :value="`${unUsedSaleAttr.id}:${unUsedSaleAttr.name}`"
          ></el-option>
        </el-select>

        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!saleAttrIdName"
          @click="addSaleAttr"
        >添加销售属性</el-button>

        <el-table
          border
          style="width: 100%"
          :data="spuForm.spuSaleAttrList"
        >
          <el-table-column
            type="index"
            align="center"
            prop="prop"
            label="序号"
            width="80"
          >
          </el-table-column>
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值名称列表"
            width="width"
          >
            <template slot-scope="{row}">
              <!-- @close="handleClose(tag)" 点击x的时候再用 -->
              <el-tag
                v-for="(spuSaleAttrValue,index) in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index,1)"
              >
                {{spuSaleAttrValue.saleAttrValueName}}
              </el-tag>

              <!-- v-model="row.inputValue" 就算这个属性不存在 用户只要输入了东西 这个属性就会自动创建并且响应式 -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.saleAttrValueName"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>

              <el-button
                @click="showInput(row)"
                v-else
                class="button-new-tag"
                size="small"
              >+ 添加</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="150"
          >
            <template slot-scope="{$index}">
              <HintButton
                type="danger"
                icon="el-icon-delete"
                title="删除销售属性"
                size="mini"
                @click="spuForm.spuSaleAttrList.splice($index,1)"
              ></HintButton>
            </template>

          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="save"
        >保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>

    </el-form>

  </div>
</template>

<script>
export default {
  name: "SpuForm",
  props: ["visible"],
  data() {
    return {
      dialogImageUrl: "", //预览大图当中dislog内部的img图片路径
      dialogVisible: false, //点击弹出dialog

      // 下面这三个不一定对
      inputVisible: false,
      inputValue: "",
      saleAttrIdName: "",

      // spuForm目前初始化的对象是为了收集和展示添加时候的spu对象
      // 修改IDE时候 其实展示和收集的不是这个对象 是你请求回来的的那个对象
      spuForm: {
        category3Id: 0,
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [],
        category3Id: "",

        spuSaleAttrList: [], //spu自己的销售属性列表
      },
      //SPU的图片列表
      spuImageList: [], //收集图片列表 先收集到这里 最后在整理到spuForm内部
      //所有的品牌列表
      trademarkList: [],
      //所有的销售属性列表
      baseSaleAttrValue: [],
    };
  },
  methods: {
    handleSuccess(res, file, fileList) {
      // console.log(res,file,fileList)
    },
    // 删除图片的时候 需要收集图片列表
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.spuImageList = fileList;
    },
    // 预览大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 这个函数就是初始化请求数据的
    async getInitUpdateSpuFormData(row, category3Id) {
      // 根据id获取SPU详情信息
      this.category3Id = category3Id;

      const result1 = await this.$API.spu.get(row.id);
      if (result1.code === 200 || result1.code === 20000) {
        this.spuForm = result1.data;
      }

      // 获取指定SPU的id对应的图片列表
      const result2 = await this.$API.sku.getSpuImageList(row.id);
      if (result2.code === 200 || result2.code === 20000) {
        let spuImageList = result2.data;
        // 给图片全部都添加name和url

        spuImageList.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = spuImageList;
      }

      // 获取所有品牌列表
      const result3 = await this.$API.trademark.getList();
      if (result3.code === 200 || result3.code === 20000) {
        this.trademarkList = result3.data;
      }
      // 获取所有的销售属性列表
      const result4 = await this.$API.spu.getSaleAttrList();
      if (result4.code === 200 || result4.code === 20000) {
        this.baseSaleAttrValue = result4.data;
      }
    },
    async getInitAddSpuFormData(category3Id) {
      // 获取所有品牌列表
      this.category3Id = category3Id;
      const result3 = await this.$API.trademark.getList();
      if (result3.code === 200 || result3.code === 20000) {
        this.trademarkList = result3.data;
      }
      // 获取所有的销售属性列表
      const result4 = await this.$API.spu.getSaleAttrList();
      if (result4.code === 200 || result4.code === 20000) {
        this.baseSaleAttrValue = result4.data;
      }
    },
    // 点击添加销售属性按钮
    addSaleAttr() {
      let [baseSaleAttrId, saleAttrName] = this.saleAttrIdName.split(":");
      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spuForm.spuSaleAttrList.push(obj);
      this.saleAttrIdName = "";
    },
    // 点击添加按钮切换为input
    showInput(row) {
      // row.inputVisible = true
      this.$set(row, "inputVisible", true);
      this.$set(row, "saleAttrValueName", "");

      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    // input失去焦点 把刚才收集的用户输入的数据 获取到 变为一个对象 添加到row.spuSaveAttrValueList当中
    handleInputConfirm(row) {
      let { saleAttrValueName, baseSaleAttrId } = row;
      let obj = { saleAttrValueName, baseSaleAttrId };

      // 判断数据如果为空 不发请求
      if (saleAttrValueName.trim() === "") {
        row.inputVisible = false;
        saleAttrValueName = "";
        return;
      }
      let isRepeat = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName === saleAttrValueName
      );
      if (isRepeat) {
        this.$message.success("属性值不能重复");
        row.saleAttrValueName = "";
        return;
      }

      row.spuSaleAttrValueList.push(obj);

      // 清空当前input
      row.saleAttrValueName = "";
      // input切换为button
      row.inputVisible = false;
    },
    // 保存
    async save() {
      // 获取请求参数
      let { spuForm, spuImageList, category3Id } = this;
      // 整理参数
      // 1、整理图片数据结构
      // 2、整理category3Id
      // 3、去掉所有销售属性身上不需要的属性
      spuForm.category3Id = category3Id;

      spuForm.spuImageList = spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data,
        };
      });
      spuForm.spuSaleAttrList.forEach((item) => {
        delete item.inputVisible;
        delete item.saleAttrValueName;
      });
      // 发请求
      try {
        const result = await this.$API.spu.addUpdate(spuForm);
        if (result.code === 200 || reuslt.code === 20000) {
          this.$message.success("保存spu成功");
          this.$emit("update:visible", false);

          // 再次出发另外一个自定义事件 告诉爹回来了
          this.$emit("backSuccess");
          // 清空data当中所有的数据
          this.resetData();
        } else {
          this.$message.error("保存spu失败");
        }
      } catch (error) {
        this.$message.error("保存spu请求失败");
      }

      // 成功干啥
      // 失败干啥
    },
    // 清空deta的数据
    resetData() {
      (this.dialogImageUrl = ""), //预览大图当中dislog内部的img图片路径
        (this.dialogVisible = false), //点击弹出dialog
        (this.saleAttrIdName = "");
      // spuForm目前初始化的对象是为了收集和展示添加时候的spu对象
      // 修改IDE时候 其实展示和收集的不是这个对象 是你请求回来的的那个对象
      (this.spuForm = {}),
        //SPU的图片列表
        (this.category3Id = "");
      (this.spuImageList = []), //收集图片列表 先收集到这里 最后在整理到spuForm内部
        //所有的品牌列表
        (this.trademarkList = []),
        //所有的销售属性列表
        (this.baseSaleAttrValue = []);
    },
    // 取消
    cancel() {
      // 返回到父组件
      this.$emit("update:visible", false);
      // 清空数据
      this.resetData();
      // 清空父组件的标志位
      this.$emit("cancelBack");
    },
  },
  computed: {
    unUsedSaleAttrList() {
      // 从总的列表当中过滤 和小的列表当中名字都不一样的项
      // return this.baseSaleAttrValue.filter(item=>{
      //   return this.spuForm.spuSaleAttrList.every(item1=>{
      //     return item.name !== item1.saleAttrName
      //   })
      // })
      return this.baseSaleAttrValue.filter((item) => {
        return this.spuForm.spuSaleAttrList.every((item1) => {
          return item.name !== item1.saleAttrName;
        });
      });
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
